var tempI = 1;
var tempF = 1;
// 允许上传的图片类型
var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
// 1024KB，也就是 1MB
var maxSize = 1024 * 1024 * 5;
// 图片最大宽度
var maxWidth = 300;
// 最大上传图片数量
var maxCount = 1;
//上传文件
var $uploaderFiles = $('.weui_uploader_files');
// 删除文件按钮
var $delBtn = $('.weui-icon-delete');
// 上传的图片地址
var URL = '';
// 图片地址数组
var URLARR = [];

var _ADINFO = [],
    _TEMPID = '';
$(function() {
    var loading = weui.loading('loading', { className: 'custom-classname' });
	var result = Model.gift.myAdvertise();
	if (result.code) {
		Common.fn.formatOutput(result);
		loading.hide();
		return false;
    }
    var res = result.data;
    _ADINFO = result.data;
    for(var i = 0;i < res.length;i++) {
        var item = '<div class="inte-ad-list" data-id="' + res[i].advertiseId + '"><p><span class="text-1-6">广告位' + parseInt(i + 1) + '</span><span class="inte-ad-now text-1-4">';
        if(res[i].picture != '') {
            item += '已设置图片</span>';
        }else {
            item += '未设置图片</span>';
        }        
        item += '<span class="inte-ad-state text-1-8 color-orange">已拍中</span></p></div>';
        $('.inte-ad-lists').append(item);
    }
    loading.hide();
});

// 点击广告位
$(document).on('click', '.inte-ad-list', function() {
    $('.shade').show();
    $('.ad-block').show();
    _TEMPID = $(this).attr('data-id');
    // 显示广告图片
    for(var i = 0;i < _ADINFO.length;i++) {
        if (_ADINFO[i].advertiseId == _TEMPID) {
			$('.ad-img').attr('src', _ADINFO[i].picture);
		}
    }
    
});

// 广告位弹窗取消
$(document).on('click', '.ad-cancel-btn', function() {
    $('.shade').hide();
	$('.ad-block').hide();
});

// 广告位弹窗确定
$(document).on('click', '.ad-submit-btn', function() {
    var loading = weui.loading('loading', { className: 'custom-classname' });
	var result = Model.gift.setPicture({ advertiseId: _TEMPID, picture: URLARR[0].url });
	if (result.code) {
		Common.fn.formatOutput(result);
		loading.hide();
		return false;
    }
    location.reload();
    loading.hide();
});

function fileChange(obj) {
    var files = obj[0].files;
	// 如果没有选中文件，直接返回
	if (files.length === 0) {
		return;
	}
	for (var i = 0, len = files.length; i < len; i++) {
		var file = files[i];
		var reader = new FileReader();
		// 如果类型不在允许的类型范围内
		if (allowTypes.indexOf(file.type) === -1) {
			weui.alert('该类型不允许上传');
			continue;
		}
		if (file.size > maxSize) {
			weui.alert('图片太大，不允许上传');
			continue;
		}
		reader.onload = function(e) {
			var img = new Image();
			var time = new Date().getTime();
			var fileid = 'file' + time;
			img.onload = function() {
				// 不要超出最大宽度
				var w = Math.min(maxWidth, img.width);
				// 高度按比例计算
				var h = img.height * (w / img.width);
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				// 设置 canvas 的宽度和高度
				canvas.width = w;
				canvas.height = h;
				ctx.drawImage(img, 0, 0, w, h);
                var base64 = canvas.toDataURL('image/png');
                // 更换图片
                $('.ad-img').attr('src', base64);
				/* // 插入到预览区
				var $preview = $(
					'<li class="weui_uploader_file weui_uploader_status" data-num="' +
						tempI +
						'" i' +
						'd="' +
						fileid +
						'" style="background-image:url(' +
						base64 +
						');position: relat' +
						'ive;"><a href="javascript:;" class="close-btn"><img src="../img/icon/close.png' +
						'" class="upload-item-close"></a><div class="weui_uploader_status_content">0%</' +
						'div></li>'
				); */
				// $uploaderFiles.append($preview);
                var num = URLARR.length;
				/* // 删除图片按钮
				$('.close-btn').on('click', function() {
					var that = $(this).parent();
					delBtn(that);
				});
				//点击删除按钮，删除相应已上传图片
				function delBtn(that) {
					// 删除对应的上传文件
					var item = that.attr('data-num');
					$('#file-' + item).remove();
					//对应的图片删除
					that.remove();
					//删除后，重新计算当前剩余图片数量 end 删除数组中对应的图片信息
					for (var i = 0; i < URLARR.length; i++) {
						if (URLARR[i].id == item) {
							URLARR.splice(i, 1);
						}
					}
				} */
				var progress = 0;

                var loading = weui.loading('正在上传中...', { className: 'custom-classname' });
				function uploading() {
                    progress++;
					// $preview.find('.weui_uploader_status_content').text(progress++ + '%');
                    // 上传文件个数大于最大个数时，提示最多只能上传图片数量，清空图片和计数器
					if (URLARR.length >= maxCount) {
						weui.alert('只能上传一张图片');
                        return false;
					} else {
						// 进度小于100%时，上传继续
						if (progress <= 100) {
							// 禁用上传按钮
							/* $('#file-' + tempI).attr('disabled', true);
							$('#showTooltips').removeClass('submit-btn');
							$('#showTooltips').text('图片上传中...'); */
							setTimeout(uploading, 20);
						} else {
									// 进度达到100%时，上传完毕，并当上传数量至少大于1时，提示文件上传成功 如果是失败，塞一个失败图标
									/* $preview
								.removeClass('weui_uploader_status')
								.find('.weui_uploader_status_content')
                                .remove(); */
									$('.uploads-files').append(obj);
									obj.css('display', 'none');
									obj.attr('disabled', false);
									// 进行图片上传
									var formData = new FormData($('#uploadform')[0]),
                                        result = Model.uploads.do(formData);
									URL = result;
									URLARR.push({ id: tempF, url: URL });
									tempF++;
									/* $('#showTooltips').text('确定');
							$('#showTooltips').addClass('submit-btn'); */
									tempI++;
									// 生成新的input
									// $('#uploadform').append('<input class="weui_uploader_input js_file" name="file" id="file-' + tempI + '"' + ' type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="multi' + 'ple" onchange="fileChange($(this))" />');
                                    // 图片上传成功
                                    loading.hide();
                                    weui.toast('图片已上传成功，点击确定替换广告');
                                    console.log(URLARR);
								}
					}
                }
				setTimeout(uploading, 20);
			};
			img.src = e.target.result;
		};
        reader.readAsDataURL(file);
	}
}
